package com.tbb.app.base.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tbb.app.base.dto.ChannelAddDTO;
import com.tbb.app.base.dto.ChannelUpdateDTO;
import com.tbb.app.base.entity.Channel;
import com.tbb.app.base.mapper.ChannelMapper;
import com.tbb.app.base.search.ChannelPageSearch;
import com.tbb.app.base.service.IChannelService;
import com.tbb.app.base.vo.ChannelVO;
import com.tbb.app.common.exception.BusinessException;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 频道表 服务实现类
 *
 * @author Liu
 * @since 2022-01-11
 */
@Service
public class ChannelServiceImpl extends ServiceImpl<ChannelMapper, Channel> implements IChannelService {

    @Override
    public List<ChannelVO> listVO() {
        QueryWrapper<Channel> wrapper = new QueryWrapper<>();
        wrapper.lambda().orderByAsc(Channel::getId);
        return this.list(wrapper).stream().map(ChannelVO::new).collect(Collectors.toList());
    }

    @Override
    public IPage<ChannelVO> page(ChannelPageSearch search) {
        IPage<Channel> page = new Page<>(search.getCurrentPage(), search.getPageSize());
        QueryWrapper<Channel> wrapper = new QueryWrapper<>();
        wrapper.lambda().orderByDesc(Channel::getUpdateTime);
        if (!StringUtils.isEmpty(search.getName())) {
            wrapper.lambda().like(Channel::getName, search.getName());
        }
        return this.page(page, wrapper).convert(ChannelVO::new);
    }

    @Override
    public void add(ChannelAddDTO dto) {
        QueryWrapper<Channel> wrapper = new QueryWrapper<>();
        wrapper.lambda().eq(Channel::getName, dto.getName());
        if (this.count(wrapper) > 0) {
            throw new BusinessException("该频道名称已存在");
        } else {
            Channel channel = new Channel(dto.getName());
            this.save(channel);
        }
    }

    @Override
    public void update(ChannelUpdateDTO dto) {
        QueryWrapper<Channel> wrapper = new QueryWrapper<>();
        wrapper.lambda().eq(Channel::getName, dto.getName())
                .ne(Channel::getId, dto.getId());
        if (this.count(wrapper) > 0) {
            throw new BusinessException("该频道名称已存在");
        } else {
            Channel channel = this.getById(dto.getId());
            if (channel == null) {
                throw new BusinessException("频道不存在");
            } else {
                channel.setName(dto.getName());
                this.updateById(channel);
            }

        }
    }
}
